package com.yedou.service.impl;

import com.alibaba.fastjson.JSON;
import com.yedou.es.Item;
import com.yedou.service.ItemService;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    private RestHighLevelClient client;

    private static final String INDEX_NAME = "items";

    @Override
    public String insertItem(Item item) {

        try {
            // 创建索引请求
            IndexRequest request = new IndexRequest(INDEX_NAME);

            // 设置文档ID（如果不设置，Elasticsearch会自动生成）
            if (item.getId() != null) {
                request.id(item.getId());
            }

            // 将对象转换为JSON并设置为请求体
            request.source(JSON.toJSONString(item), XContentType.JSON);

            // 执行请求
            IndexResponse response = client.index(request, RequestOptions.DEFAULT);

            // 返回生成的文档ID
            return response.getId();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("插入文档失败", e);
        }
    }
}
